package com.qili.core.filter;

/**
 * @author zhaoyongke
 * @date 2021/8/25
 * @description
 */


import com.qili.util.EscapeUtil;
import com.qili.util.FilterCoreUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 类 {@code XssHttpServletRequestWrapper} Xss核心匹配类 <br> .
 *
 * 本软件仅对本次教程负责，版权所有 <a href="http://www.cnhuashao.com">中国，華少</a><br>
 *
 * @author cnHuaShao
 * <a href="mailto:lz2392504@gmail.com
 * <p>
 * ">cnHuaShao</a>
 * 修改备注：
 * @version v1.0.1 2019/11/5 19:30
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper
{

    /**
     * 需要进行过滤的请求
     */
    HttpServletRequest orgRequest = null;
    /**
     * 是否启用过滤
     */
    private boolean isIncludeRichText = false;

    /**
     * 深度过滤构造方法
     * @param request 需要过滤的请求
     * @param isIncludeRichText 是否进行过滤，默认false
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) {
        super(request);
        orgRequest = request;
        this.isIncludeRichText = isIncludeRichText;
    }


    @Override
    public String getParameter(String name) {
        Boolean flag = ("content".equals(name) || name.endsWith("WithHtml"));
        if( flag && !isIncludeRichText){
            return super.getParameter(name);
        }
        name = FilterCoreUtil.clean(name);
        String value = super.getParameter(name);
        if (StringUtils.isNotBlank(value)) {
            value = EscapeUtil.clean(value).trim();
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name)
    {
        String[] values = super.getParameterValues(name);
        if (values != null)
        {
            int length = values.length;
            String[] escapseValues = new String[length];
            for (int i = 0; i < length; i++)
            {
                // 防xss攻击和过滤前后空格
                escapseValues[i] = EscapeUtil.clean(values[i]).trim();
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }
}
